package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 使用特定的构造器实例化对象
 */
public class ReflectDemo3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Person p = new Person("李四",22);
        System.out.println(p);

        Class cls = Class.forName("reflect.Person");
        /*
            Class对象提供了获取其表示的类对应构造器的操作:
            Constructor getConstructor(参数列表对应的类对象)

            java.lang.reflect.Constructor类，构造器对象
            它也是反射对象之一，它的每一个实例仅表示一个构造器的相关信息
         */
        Constructor c = cls.getConstructor(String.class,int.class);//Person(String,int)
        Object obj = c.newInstance("王五",33);//new Person("王五",33);
        System.out.println(obj);

        //获取无参构造器
        Constructor c1 = cls.getConstructor();//获取无参构造器
        Object obj1 = c1.newInstance();//不需要传入实参  new Person();
        System.out.println(obj1);


    }
}






